package com.lagou.rpc.server;

import com.lagou.rpc.entity.RpcRequest;
import com.lagou.rpc.protocol.JSONSerializer;
import com.lagou.rpc.protocol.RpcDecoder;
import com.lagou.rpc.protocol.RpcEncoder;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
public class NettyServer implements CommandLineRunner {

    /**
     * 启动netty server
     * @param host
     * @param port
     * @throws Exception
     */
    public void start(String host, int port) throws Exception {
        NioEventLoopGroup nioEventLoopGroup = new NioEventLoopGroup();
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(nioEventLoopGroup).channel(NioServerSocketChannel.class)
                .childHandler(
                new ChannelInitializer<SocketChannel>() {
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline p = ch.pipeline();
                        p.addLast(new LengthFieldBasedFrameDecoder(
        65536, 0, 4, 0, 0));
                        p.addLast(new RpcDecoder(new JSONSerializer(), RpcRequest.class));
                        p.addLast(new RpcEncoder(new JSONSerializer()));
                        p.addLast(new RpcNettyHandler());

                    }
                });
        bootstrap.bind(host, port).sync();
    }

    @Override
    public void run(String... args) throws Exception {
        start("127.0.0.1", 8848);
    }
}
